package com.sirun.cn.fca.module.splash;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.sirun.cn.fca.R;
import com.sirun.cn.fca.constant.PathConst;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.ResourcesUtils;
import com.tencent.cloud.uikit.ui.BaseIovActivity;
import com.tencent.cloud.uikit.utils.PermissionUtils;

import java.util.Arrays;
import java.util.List;

import cn.sirun.com.fca.account.service.LoginManager;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

/**
 * 闪屏页
 *
 * @author showxiao
 * @date 2018/6/22
 */
public class SplashActivity extends BaseIovActivity
        implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    private static final String TAG = SplashActivity.class.getSimpleName();

    private static final int PERMISSION_REQUEST_CODE = 1;

    private static final int PERMISSION_REQUEST_CODE_EXTERNAL_STORAGE = 2;

    /**
     * 需要动态申请的权限
     */
    private static final String[] PERMISSION_ALL = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA
    };

    /**
     * 存储空间权限
     */
    private static final String[] PERMISSION_EXTERNAL_STORAGE = new String[] {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setBackgroundDrawableResource(R.drawable.bg_splash);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(cn.sirun.com.fca.account.R.color.login_bg_color));
        if (!EasyPermissions.hasPermissions(this, PERMISSION_ALL)) {
            requestAllPermissions();
        } else {
            jumpToTargetActivity();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult: requestCode = [" + requestCode
                + "], permissions = [" + permissions + "], grantResults = [" + grantResults + "]");

        int index = 0;
        for (String perms : permissions) {
            if (perms.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    || perms.contains(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                if (PackageManager.PERMISSION_GRANTED != grantResults[index]) {
                    if (PERMISSION_REQUEST_CODE == requestCode) {
                        // 请求所有权限，未允许存储空间权限，重新申请存储空间权限
                        requestStoragePermissions();
                    } else if (PERMISSION_REQUEST_CODE_EXTERNAL_STORAGE == requestCode) {
                        // 重新请求存储空间权限失败，退出应用
                        Toast.makeText(this, R.string.permission_request_storage_failed,
                                Toast.LENGTH_SHORT).show();
                        finish();
                    }
                    return;
                }
            }
            ++index;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults,
                this);

        jumpToTargetActivity();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsGranted: requestCode = ["
                + requestCode + "], perms = [" + perms + "]");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Log.w(TAG, "onPermissionsDenied, perms : " + Arrays.toString(perms.toArray(new
                String[perms.size()])));
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        Log.d(TAG, "onRationaleAccepted: requestCode = [" + requestCode + "]");
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        Log.w(TAG, "onRationaleDenied: requestCode = [" + requestCode + "]");
        finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult: requestCode = [" + requestCode + "], resultCode = ["
                + resultCode + "], data = [" + data + "]");

        super.onActivityResult(requestCode, resultCode, data);

        if (PermissionUtils.isSettingsPermissionRequest(requestCode)) {
            if (EasyPermissions.hasPermissions(this, PERMISSION_EXTERNAL_STORAGE)) {
                jumpToTargetActivity();
            } else {
                Toast.makeText(this, R.string.permission_request_storage_failed,
                        Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    /**
     * 申请所有权限
     */
    private void requestAllPermissions() {
        String rationale = ResourcesUtils.getString(
                R.string.permission_rationale, ResourcesUtils.getString(R.string.app_name)
        );
        PermissionRequest request = new PermissionRequest
                .Builder(this, PERMISSION_REQUEST_CODE, PERMISSION_ALL)
                .setRationale(rationale)
                .setPositiveButtonText(R.string.setup)
                .build();
        EasyPermissions.requestPermissions(request);
    }

    /**
     * 申请存储权限
     */
    private void requestStoragePermissions() {
        if (EasyPermissions.somePermissionPermanentlyDenied(
                this, Arrays.asList(PERMISSION_EXTERNAL_STORAGE))) {
            // 永久拒绝存储权限，前往系统设置进行设置
            showAppSettingsDialog();
        } else {
            // 直接弹窗提示申请存储权限
            PermissionRequest request = new PermissionRequest
                    .Builder(this, PERMISSION_REQUEST_CODE_EXTERNAL_STORAGE, PERMISSION_EXTERNAL_STORAGE)
                    .setRationale(R.string.permission_rationale_storage)
                    .setPositiveButtonText(R.string.setup)
                    .build();
            EasyPermissions.requestPermissions(request);
        }
    }

    /**
     * 前往系统设置进行设置
     */
    private void showAppSettingsDialog() {
        new AppSettingsDialog.Builder(this)
                .setTitle(R.string.permission_essential)
                .setRationale(R.string.permission_rationale_storage_setting)
                .setPositiveButton(R.string.setup)
                .build().show();
    }

    private void jumpToTargetActivity() {
        String path = LoginManager.getInstance().isLogin() ? PathConst.MAIN : PathConst.LOGIN;
//        path = PathConst.MAIN;
        Intent intent = Router.fromPath(path);
        startActivity(intent);
        finish();
        overridePendingTransition(0, 0);
    }
}